<template>
  <div id="departments">
    <!-- 面包屑导航 -->
    <el-breadcrumb
      separator="/"
      style="padding-left: 10px; padding-bottom: 10px; font-size: 12px"
    >
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>系统管理</el-breadcrumb-item>
      <el-breadcrumb-item>部门管理</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 部门列表卡片 -->
    <el-card class="box-card">
      <!-- 搜索表单 -->
      <el-form
        :inline="true"
        ref="queryForm"
        :model="queryMap"
        label-width="90px"
      >
        <el-form-item label="部门名称">
          <el-input
            @keyup.enter.native="searchDept"
            @clear="searchDept"
            clearable
            v-model="queryMap.deptName"
            placeholder="请输入部门名称查询"
            style="width: 180px"
          ></el-input>
        </el-form-item>

        <el-form-item label="部门编码">
          <el-input
            @keyup.enter.native="searchDept"
            @clear="searchDept"
            clearable
            v-model="queryMap.deptCode"
            placeholder="请输入编码（如HR-001）"
            style="width: 160px"
          ></el-input>
        </el-form-item>

        <el-form-item label="部门状态">
          <el-select
            v-model="queryMap.deptStatus"
            @change="searchDept"
            clearable
            placeholder="全部状态"
            style="width: 140px"
          >
            <el-option label="未启用" value="0"></el-option>
            <el-option label="正常" value="1"></el-option>
            <el-option label="暂停" value="2"></el-option>
            <el-option label="撤销" value="3"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="上级部门">
          <el-select
            v-model="queryMap.parentDeptId"
            @change="searchDept"
            clearable
            placeholder="全部层级"
            style="width: 180px"
          >
            <el-option label="顶级部门" value=""></el-option>
            <el-option
              v-for="dept in deptTreeOptions"
              :key="dept.id"
              :label="dept.label"
              :value="dept.id"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item style="margin-left: 30px">
          <el-button @click="resetQuery" icon="el-icon-refresh">重置</el-button>
          <el-button type="primary" @click="searchDept" icon="el-icon-search"
            >查询</el-button
          >
          <el-button
            type="success"
            icon="el-icon-plus"
            @click="openAddDialog"
            v-hasPermission="'department:add'"
            >添加部门</el-button
          >
          <el-button
            icon="el-icon-download"
            @click="exportExcel"
            v-hasPermission="'department:export'"
            >导出数据</el-button
          >
        </el-form-item>
      </el-form>

      <!-- 部门表格 -->
      <el-table
        v-loading="loading"
        :data="deptList"
        border
        style="width: 100%"
        height="400"
        @row-click="handleRowClick"
      >
        <el-table-column label="序号" type="index" width="60"></el-table-column>
        <el-table-column
          prop="deptCode"
          label="部门编码"
          width="120"
        ></el-table-column>
        <el-table-column
          prop="deptName"
          label="部门名称"
          width="160"
        ></el-table-column>
        <el-table-column
          prop="deptAbbr"
          label="部门简称"
          width="100"
        ></el-table-column>
        <el-table-column label="上级部门" width="160">
          <template slot-scope="scope">
            {{ scope.row.parentDeptName || "无" }}
          </template>
        </el-table-column>
        <el-table-column
          prop="leaderEmpId"
          label="负责人ID"
          width="120"
        ></el-table-column>
        <el-table-column label="部门状态" width="110">
          <template slot-scope="scope">
            <el-tag
              size="mini"
              :type="getStatusTagType(scope.row.deptStatus)"
              >{{ getStatusText(scope.row.deptStatus) }}</el-tag
            >
          </template>
        </el-table-column>
        <el-table-column
          prop="establishDate"
          label="成立日期"
          width="140"
          sortable
        ></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit-outline"
              @click="openEditDialog(scope.row.id)"
              v-hasPermission="'department:edit'"
              >编辑</el-button
            >
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click="deleteDept(scope.row.id)"
              v-hasPermission="'department:delete'"
              :disabled="scope.row.hasChildren"
              >删除</el-button
            >
            <el-button
              size="mini"
              type="warning"
              icon="el-icon-link"
              @click="openAssignParentDialog(scope.row.id)"
              v-hasPermission="'department:assignParent'"
              >分配上级</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页控件 -->
      <el-pagination
        style="margin-top: 15px; text-align: right"
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryMap.pageNum"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="queryMap.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>

    <!-- 1. 添加部门对话框 -->
    <el-dialog
      title="添加部门"
      :visible.sync="addDialogVisible"
      width="55%"
      @close="closeAddDialog"
    >
      <el-form
        ref="addFormRef"
        :model="addForm"
        :rules="deptFormRules"
        label-width="110px"
        label-position="right"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="部门编码" prop="deptCode">
              <el-input
                v-model="addForm.deptCode"
                placeholder="请输入编码（如HR-001、IT-002）"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="部门名称" prop="deptName">
              <el-input
                v-model="addForm.deptName"
                placeholder="请输入部门全称"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="部门简称" prop="deptAbbr">
              <el-input
                v-model="addForm.deptAbbr"
                placeholder="请输入部门简称（可选）"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="上级部门" prop="parentDeptId">
              <el-select
                v-model="addForm.parentDeptId"
                placeholder="选择上级部门（可选）"
              >
                <el-option label="顶级部门" value=""></el-option>
                <el-option
                  v-for="dept in deptTreeOptions"
                  :key="dept.id"
                  :label="dept.label"
                  :value="dept.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="负责人ID" prop="leaderEmpId">
              <el-input
                v-model="addForm.leaderEmpId"
                placeholder="请输入负责人员工ID（可选）"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="部门状态" prop="deptStatus">
              <el-select
                v-model="addForm.deptStatus"
                placeholder="请选择部门状态"
              >
                <el-option label="未启用" value="0"></el-option>
                <el-option label="正常" value="1"></el-option>
                <el-option label="暂停" value="2"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="成立日期" prop="establishDate">
              <el-date-picker
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择成立日期（可选）"
                v-model="addForm.establishDate"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="备注信息">
          <el-input
            type="textarea"
            v-model="addForm.remark"
            placeholder="请输入备注（可选）"
            rows="3"
          ></el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button
          type="primary"
          @click="submitAddForm"
          :loading="btnLoading"
          :disabled="btnDisabled"
          >确定添加</el-button
        >
      </div>
    </el-dialog>

    <!-- 2. 编辑部门对话框 -->
    <el-dialog
      title="编辑部门"
      :visible.sync="editDialogVisible"
      width="55%"
      @close="closeEditDialog"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="deptFormRules"
        label-width="110px"
        label-position="right"
      >
        <el-input type="hidden" v-model="editForm.id"></el-input>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="部门编码" prop="deptCode">
              <el-input
                v-model="editForm.deptCode"
                placeholder="部门编码"
                :disabled="true"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="部门名称" prop="deptName">
              <el-input
                v-model="editForm.deptName"
                placeholder="请输入部门全称"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="部门简称" prop="deptAbbr">
              <el-input
                v-model="editForm.deptAbbr"
                placeholder="请输入部门简称（可选）"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="上级部门" prop="parentDeptId">
              <el-select
                v-model="editForm.parentDeptId"
                placeholder="选择上级部门（可选）"
                :disabled="editForm.hasChildren"
              >
                <el-option label="顶级部门" value=""></el-option>
                <el-option
                  v-for="dept in deptTreeOptions"
                  :key="dept.id"
                  :label="dept.label"
                  :value="dept.id"
                  :disabled="dept.id === editForm.id"
                ></el-option>
              </el-select>
              <el-tooltip
                v-if="editForm.hasChildren"
                effect="dark"
                content="包含子部门，不可修改上级"
                placement="top"
              >
                <i
                  class="el-icon-info"
                  style="margin-left: 5px; color: #409eff"
                ></i>
              </el-tooltip>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="负责人ID" prop="leaderEmpId">
              <el-input
                v-model="editForm.leaderEmpId"
                placeholder="请输入负责人员工ID（可选）"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="部门状态" prop="deptStatus">
              <el-select
                v-model="editForm.deptStatus"
                placeholder="请选择部门状态"
              >
                <el-option label="未启用" value="0"></el-option>
                <el-option label="正常" value="1"></el-option>
                <el-option label="暂停" value="2"></el-option>
                <el-option label="撤销" value="3"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="成立日期" prop="establishDate">
              <el-date-picker
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择成立日期（可选）"
                v-model="editForm.establishDate"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="editForm.deptStatus === '3'">
            <el-form-item label="撤销日期">
              <el-date-picker
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择撤销日期"
                v-model="editForm.dissolveDate"
                :disabled="editForm.deptStatus !== '3'"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="备注信息">
          <el-input
            type="textarea"
            v-model="editForm.remark"
            placeholder="请输入备注（可选）"
            rows="3"
          ></el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button
          type="primary"
          @click="submitEditForm"
          :loading="btnLoading"
          :disabled="btnDisabled"
          >保存修改</el-button
        >
      </div>
    </el-dialog>

    <!-- 3. 分配上级部门对话框 -->
    <el-dialog
      title="分配上级部门"
      :visible.sync="assignParentDialogVisible"
      width="40%"
      @close="closeAssignParentDialog"
    >
      <el-form
        ref="assignFormRef"
        :model="assignForm"
        label-width="110px"
        label-position="right"
      >
        <el-form-item label="当前部门">
          <el-input
            v-model="assignForm.currentDeptName"
            :disabled="true"
          ></el-input>
        </el-form-item>
        <el-form-item label="上级部门" prop="parentDeptId">
          <el-select
            v-model="assignForm.parentDeptId"
            placeholder="选择上级部门"
            style="width: 100%"
          >
            <el-option label="设为顶级部门" value=""></el-option>
            <el-option
              v-for="dept in deptTreeOptions"
              :key="dept.id"
              :label="dept.label"
              :value="dept.id"
              :disabled="dept.id === assignForm.currentDeptId"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="assignParentDialogVisible = false">取消</el-button>
        <el-button
          type="primary"
          @click="submitAssignParent"
          :loading="btnLoading"
          :disabled="btnDisabled"
          v-hasPermission="'department:assignParent'"
          >确认分配</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "Departments",
  data() {
    // 部门编码验证（支持字母、数字、横杠、下划线，1-30字符）
    const validateDeptCode = (rule, value, callback) => {
      const reg = /^[A-Za-z0-9_-]{1,30}$/;
      if (!value) {
        return callback(new Error("部门编码不能为空"));
      }
      if (!reg.test(value)) {
        return callback(
          new Error("编码仅支持字母、数字、横杠、下划线，长度1-30字符")
        );
      }
      callback();
    };

    // 部门名称验证（1-100字符）
    const validateDeptName = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("部门名称不能为空"));
      }
      if (value.length > 100) {
        return callback(new Error("部门名称长度不能超过100字符"));
      }
      callback();
    };

    // 部门状态验证（必选）
    const validateDeptStatus = (rule, value, callback) => {
      if (value === undefined || value === "") {
        return callback(new Error("请选择部门状态"));
      }
      callback();
    };

    return {
      // 加载状态
      loading: true,
      btnLoading: false,
      btnDisabled: false,

      // 分页与查询条件
      total: 0,
      queryMap: {
        pageNum: 1,
        pageSize: 5,
        deptName: "",
        deptCode: "",
        deptStatus: "",
        parentDeptId: "",
      },

      // 部门列表数据（包含上级部门名称、是否有子部门）
      deptList: [],
      // 部门树形结构（用于上级部门选择器）
      deptTreeOptions: [],

      // 对话框控制
      addDialogVisible: false,
      editDialogVisible: false,
      assignParentDialogVisible: false,

      // 表单数据
      addForm: {
        deptCode: "",
        deptName: "",
        deptAbbr: "",
        parentDeptId: "",
        leaderEmpId: "",
        deptStatus: "1", // 默认正常状态
        establishDate: "",
        remark: "",
      },
      editForm: {},
      assignForm: {
        currentDeptId: "",
        currentDeptName: "",
        parentDeptId: "",
      },

      // 表单验证规则
      deptFormRules: {
        deptCode: [{ validator: validateDeptCode, trigger: "blur" }],
        deptName: [{ validator: validateDeptName, trigger: "blur" }],
        deptStatus: [{ validator: validateDeptStatus, trigger: "change" }],
        deptAbbr: [
          { max: 20, message: "简称长度不能超过20字符", trigger: "blur" },
        ],
        leaderEmpId: [
          { pattern: /^\d*$/, message: "负责人ID必须为数字", trigger: "blur" },
        ],
      },
      assignFormRules: {
        parentDeptId: [
          { required: true, message: "请选择上级部门", trigger: "change" },
        ],
      },
    };
  },

  created() {
    // 初始化加载部门列表和部门树形结构
    this.loadDeptList();
    this.loadDeptTree();
  },

  methods: {
    /**
     * 1. 基础工具方法
     */
    // 根据状态值获取显示文本
    getStatusText(status) {
      const statusMap = {
        0: "未启用",
        1: "正常",
        2: "暂停",
        3: "撤销",
      };
      return statusMap[status] || "未知";
    },

    // 根据状态值获取标签类型
    getStatusTagType(status) {
      const typeMap = {
        0: "default", // 灰色
        1: "success", // 绿色
        2: "warning", // 橙色
        3: "danger", // 红色
      };
      return typeMap[status] || "default";
    },

    /**
     * 2. 列表加载与查询
     */
    // 加载部门列表
    async loadDeptList() {
      this.loading = true;
      try {
        const { data: res } = await this.$http.get("/department/findDeptList", {
          params: this.queryMap,
        });
        if (res.code !== 200) {
          return this.$message.error("加载部门列表失败：" + res.msg);
        }
        // 处理部门列表（添加上级部门名称、是否有子部门标记）
        this.deptList = res.data.rows.map((dept) => {
          // 匹配上级部门名称
          const parentDept = this.deptTreeOptions.find(
            (item) => item.id === dept.parentDeptId
          );
          // 标记是否有子部门（通过树形结构判断）
          const hasChildren = this.deptTreeOptions.some(
            (item) => item.parentId === dept.id
          );
          return {
            ...dept,
            parentDeptName: parentDept ? parentDept.label : "",
            hasChildren,
          };
        });
        this.total = res.data.total;
      } catch (err) {
        this.$message.error("加载部门列表异常：" + err.message);
      } finally {
        this.loading = false;
      }
    },

    // 加载部门树形结构（用于上级部门选择器）
    async loadDeptTree() {
      try {
        const { data: res } = await this.$http.get("/department/findDeptTree");
        if (res.code !== 200) {
          return this.$message.error("加载部门树形结构失败：" + res.msg);
        }
        // 转换为下拉选择器格式（id, label, parentId）
        this.deptTreeOptions = this.formatTreeToOptions(res.data);
      } catch (err) {
        this.$message.error("加载部门树形结构异常：" + err.message);
      }
    },

    // 格式化树形结构为下拉选择器选项（带层级显示）
    formatTreeToOptions(tree, level = 0, parentId = "") {
      let options = [];
      const prefix = "　　".repeat(level); // 层级缩进（全角空格）
      tree.forEach((node) => {
        options.push({
          id: node.id,
          label: level === 0 ? node.deptName : `${prefix}└─${node.deptName}`,
          parentId,
        });
        // 递归处理子节点
        if (node.children && node.children.length > 0) {
          options = options.concat(
            this.formatTreeToOptions(node.children, level + 1, node.id)
          );
        }
      });
      return options;
    },

    // 搜索部门
    searchDept() {
      this.queryMap.pageNum = 1; // 重置页码
      this.loadDeptList();
    },

    // 重置查询条件
    resetQuery() {
      this.queryMap = {
        pageNum: 1,
        pageSize: 5,
        deptName: "",
        deptCode: "",
        deptStatus: "",
        parentDeptId: "",
      };
      this.loadDeptList();
    },

    /**
     * 3. 分页控制
     */
    handleSizeChange(pageSize) {
      this.queryMap.pageSize = pageSize;
      this.loadDeptList();
    },

    handleCurrentChange(pageNum) {
      this.queryMap.pageNum = pageNum;
      this.loadDeptList();
    },

    /**
     * 4. 对话框操作（添加/编辑/分配上级）
     */
    // 打开添加对话框
    openAddDialog() {
      this.addForm = {
        deptCode: "",
        deptName: "",
        deptAbbr: "",
        parentDeptId: "",
        leaderEmpId: "",
        deptStatus: "1",
        establishDate: "",
        remark: "",
      };
      this.addDialogVisible = true;
    },

    // 关闭添加对话框
    closeAddDialog() {
      this.$refs.addFormRef?.clearValidate();
    },

    // 提交添加表单
    async submitAddForm() {
      this.$refs.addFormRef.validate(async (isValid) => {
        if (!isValid) return;

        this.btnLoading = true;
        this.btnDisabled = true;
        try {
          const { data: res } = await this.$http.post(
            "/department/add",
            this.addForm
          );
          if (res.code === 200) {
            this.$notify.success({
              title: "操作成功",
              message: "部门添加成功",
            });
            this.addDialogVisible = false;
            this.loadDeptList();
            this.loadDeptTree(); // 刷新树形结构
          } else {
            this.$message.error("添加失败：" + res.msg);
          }
        } catch (err) {
          this.$message.error("添加异常：" + err.message);
        } finally {
          this.btnLoading = false;
          this.btnDisabled = false;
        }
      });
    },

    // 打开编辑对话框
    async openEditDialog(deptId) {
      try {
        const { data: res } = await this.$http.get(
          `/department/edit/${deptId}`
        );
        if (res.code !== 200) {
          return this.$message.error("加载部门信息失败：" + res.msg);
        }
        // 处理日期格式（后端返回可能为字符串，适配日期选择器）
        this.editForm = {
          ...res.data,
          establishDate: res.data.establishDate || "",
          dissolveDate: res.data.dissolveDate || "",
          // 标记是否有子部门
          hasChildren: this.deptTreeOptions.some(
            (item) => item.parentId === deptId
          ),
        };
        this.editDialogVisible = true;
      } catch (err) {
        this.$message.error("加载部门信息异常：" + err.message);
      }
    },

    // 关闭编辑对话框
    closeEditDialog() {
      this.$refs.editFormRef?.clearValidate();
      this.editForm = {};
    },

    // 提交编辑表单
    async submitEditForm() {
      this.$refs.editFormRef.validate(async (isValid) => {
        if (!isValid) return;

        this.btnLoading = true;
        this.btnDisabled = true;
        try {
          const { data: res } = await this.$http.put(
            `/department/update/${this.editForm.id}`,
            this.editForm
          );
          if (res.code === 200) {
            this.$notify.success({
              title: "操作成功",
              message: "部门修改成功",
            });
            this.editDialogVisible = false;
            this.loadDeptList();
            this.loadDeptTree(); // 刷新树形结构
          } else {
            this.$message.error("修改失败：" + res.msg);
          }
        } catch (err) {
          this.$message.error("修改异常：" + err.message);
        } finally {
          this.btnLoading = false;
          this.btnDisabled = false;
        }
      });
    },

    // 打开分配上级对话框
    async openAssignParentDialog(deptId) {
      try {
        // 获取当前部门信息
        const { data: res } = await this.$http.get(
          `/department/info/${deptId}`
        );
        if (res.code !== 200) {
          return this.$message.error("加载部门信息失败：" + res.msg);
        }
        // 初始化分配表单
        this.assignForm = {
          currentDeptId: deptId,
          currentDeptName: res.data.deptName,
          parentDeptId: res.data.parentDeptId || "",
        };
        this.assignParentDialogVisible = true;
      } catch (err) {
        this.$message.error("加载部门信息异常：" + err.message);
      }
    },

    // 关闭分配上级对话框
    closeAssignParentDialog() {
      this.$refs.assignFormRef?.clearValidate();
      this.assignForm = {};
    },

    // 提交上级部门分配
    async submitAssignParent() {
      this.$refs.assignFormRef.validate(async (isValid) => {
        if (!isValid) return;

        this.btnLoading = true;
        this.btnDisabled = true;
        try {
          const { data: res } = await this.$http.post(
            `/department/${this.assignForm.currentDeptId}/assignParent`,
            { parentDeptId: this.assignForm.parentDeptId }
          );
          if (res.code === 200) {
            this.$notify.success({
              title: "操作成功",
              message: "上级部门分配成功",
            });
            this.assignParentDialogVisible = false;
            this.loadDeptList();
            this.loadDeptTree(); // 刷新树形结构
          } else {
            this.$message.error("分配失败：" + res.msg);
          }
        } catch (err) {
          this.$message.error("分配异常：" + err.message);
        } finally {
          this.btnLoading = false;
          this.btnDisabled = false;
        }
      });
    },

    /**
     * 5. 删除部门
     */
    async deleteDept(deptId) {
      const confirmRes = await this.$confirm(
        "此操作将永久删除该部门（若有子部门请先删除子部门），是否继续？",
        "删除确认",
        {
          confirmButtonText: "确定删除",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch(() => {});

      if (confirmRes !== "confirm") return;

      try {
        const { data: res } = await this.$http.delete(
          `/department/delete/${deptId}`
        );
        if (res.code === 200) {
          this.$notify.success({ title: "操作成功", message: "部门删除成功" });
          this.loadDeptList();
          this.loadDeptTree(); // 刷新树形结构
        } else {
          this.$message.error("删除失败：" + res.msg);
        }
      } catch (err) {
        this.$message.error("删除异常：" + err.message);
      }
    },

    /**
     * 6. 导出Excel
     */
    async exportExcel() {
      try {
        const res = await this.$http.request({
          url: "/department/excel",
          method: "post",
          responseType: "blob",
        });

        // 处理权限不足（返回JSON而非blob）
        if (res.headers["content-type"].includes("application/json")) {
          const blob = new Blob([res.data], { type: "application/json" });
          const reader = new FileReader();
          reader.onload = () => {
            const errData = JSON.parse(reader.result);
            this.$message.error("导出失败：" + (errData.msg || "无导出权限"));
          };
          reader.readAsText(blob);
          return;
        }

        // 正常导出文件
        const blob = new Blob([res.data], { type: "application/vnd.ms-excel" });
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement("a");
        a.href = url;
        a.download = `部门列表_${new Date().toLocaleDateString()}.xls`;
        document.body.appendChild(a);
        a.click();
        window.URL.revokeObjectURL(url);
        document.body.removeChild(a);
      } catch (err) {
        this.$message.error("导出异常：" + err.message);
      }
    },

    /**
     * 7. 表格行点击事件（可选）
     */
    handleRowClick(row) {
      // 可添加行点击选中逻辑
    },
  },
};
</script>

<style scoped>
/* 自定义表格行 hover 效果 */
#departments .el-table tr:hover {
  background-color: #fafafa;
}
/* 对话框表单间距优化 */
.el-form-item {
  margin-bottom: 20px;
}
/* 层级选择器缩进优化 */
.el-select-dropdown__item {
  white-space: nowrap;
}
</style>
